package com.qlp.start.Task;

import com.qlp.start.Mapper.TestMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;


/**
 * @author itoutsource.cz10
 * 接口方式开启事务
 */
@Component
@Configuration
@EnableScheduling   //开启事务
public class DynamicScheduleTask implements SchedulingConfigurer {

    @Autowired
    private TestMapper testMapper;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(
                //添加runnable
                () ->System.out.println("-----开始执行任务------"+ LocalDateTime.now().toLocalTime()),
                //设置执行周期
                triggerContext -> {
                    //从数据库获取执行周期
                    String corn=testMapper.getCorn();
                    //合法性校验
                    if(StringUtils.isEmpty(corn)){
                        System.out.println("错误格式的时间");
                    }
                    return new CronTrigger(corn).nextExecutionTime(triggerContext);
                }
        );
    }
}
